<template>
  <div>
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="queryForm.account" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="queryForm.userName" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryForm.mobile" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="queryForm.email" placeholder="请输入邮箱" clearable />
      </el-form-item>
      <!-- <el-form-item label="注册时间" sortable >
        <el-date-picker
          v-model="daterange"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="warning" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="action-buttons">
    <el-button type="primary" class="custom-btn" @click="downloadTemplate">
      <el-icon class="icon"><Download /></el-icon>下载模板
    </el-button>
    <el-button type="primary" class="custom-btn" @click="dataVisible = true">
      <el-icon class="icon"><FolderAdd /></el-icon>数据导入
    </el-button>
    <el-button type="success" class="custom-btn" @click="visible = true">
      <el-icon class="icon"><Upload /></el-icon>上传模板
    </el-button>
    <el-button type="primary" class="custom-btn" @click="handleAdd">
      <el-icon class="icon"><Plus /></el-icon>新增
    </el-button>
  </div>
  

    <el-table v-loading="loading" :data="list"
    border
    style="width: 100%; min-width: 800px; border-radius: 12px; overflow: hidden; box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.1);"
    :header-cell-style="{ backgroundImage: 'linear-gradient(to right, #f0f9ff, #e5eaff)', color: '#333', fontWeight: 'bold' }"
    :cell-style="{ padding: '12px 8px' }"
    fit>
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="姓名" align="center" prop="account"  />
      <el-table-column label="用户名" align="center" prop="username"  />
      <el-table-column label="角色" align="center">
        <template #default="scope">
          {{ scope.row.permissions === 'admin' ? '管理员' : '普通用户' }}
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="注册时间" align="center" prop="createTime" sortable />
      <el-table-column label="操作" align="center" width="400">
        <template #default="scope">
          <div class="button-group">
          <el-button link type="primary" class="btn-design" icon="Edit" @click="handleUpdate(scope.row.userId)">修改</el-button>
          <el-button link type="primary" class="btn-delete" icon="Delete" @click="handleDelete(scope.row.userId)">删除</el-button>
          <el-button link type="warning" class="btn-suspend" @click="resetPassword(scope.row.userId)">
            <el-icon class="icon"><Refresh /></el-icon>重置密码</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      v-model:page-size="queryForm.pageSize"
      v-model:current-page="queryForm.pageNo"
      :total="total"
      @current-change="getList"
    />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="open" :title="title" width="700px" append-to-body :close-on-click-modal="false" :modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="姓名" prop="account">
              <el-input v-model="form.account" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="form.deptId" filterable placeholder="部门">
                <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="form.permissions" filterable placeholder="角色">
                <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="visible" title="上传模板" width="500px" @close="reset">
      <el-upload
        class="upload-demo"
        drag
        :action="apiUrl + '/common/template'"
        :on-success="handleTemplateUploadSuccess"
        :on-error="handleTemplateUploadError"
        :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drag file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只支持xlsx文件，文件大小不超过5MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button type="primary" @click="closeDialog">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="dataVisible" title="数据导入" width="500px" @close="reset">
      <el-upload
        class="upload-demo"
        drag
        :action="apiUrl+'/sysUser/batchSave'"
        :on-success="handleDataImportSuccess"
        :on-error="handleDataImportError"
        :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drag file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只支持xlsx文件，文件大小不超过5MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button type="primary" @click="closedataDialog">确 定</el-button>
        <el-button @click="closedataDialog">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, toRef,watch ,onMounted} from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import { UploadFilled } from '@element-plus/icons-vue';
import { debounce } from "lodash-es";

// 查询参数
const queryForm = reactive({
  account: "",
  userName: "",
  mobile: "",
  email: "",
  startTime: "",
  endTime: "",
  pageNo: 1,
  pageSize: 10,
});

const apiUrl = ref(import.meta.env.VITE_APP_API);
// 列表内容数量
const total = ref(0);
const daterange = ref([]);
// 列表是否加载
const loading = ref(true);
// 列表返回值
const list = ref<any[]>([]);

// const props = defineProps({
//   visible: {
//     type: Boolean,
//     required: true
//   },
//   action: {
//     type: String,
//     required: true
//   }
// });

const emit = defineEmits(['update:visible']);
// 控制上传对话框的显示
const visible = ref(false);
const dataVisible = ref(false);
// 处理模板上传成功
const handleTemplateUploadSuccess = (response) => {
  // 检查response对象中是否有msg字段，并显示对应的消息
  if (response && response.msg) {
    ElMessage.success(response.msg); // 使用Element UI的消息提示
  } else {
    ElMessage.success("模板上传成功"); // 默认成功消息
  }
  closedataDialog();
};

// 处理模板上传错误
const handleTemplateUploadError = (error) => {
  // 检查error对象中是否有msg字段，并显示对应的消息
  if (error && error.response && error.response.data && error.response.data.msg) {
    ElMessage.error(error.response.data.msg); // 使用Element UI的消息提示
  } else {
    ElMessage.error("模板上传失败"); // 默认失败消息
  }
};

// 处理数据导入成功
const handleDataImportSuccess = (response) => {
  console.log("数据导入之后返回的数据 " + JSON.stringify(response));
  // 检查response对象中是否有msg字段，并显示对应的消息
  if (response && response.msg) {
    ElMessage.success(response.msg); // 使用Element UI的消息提示
  } else {
    ElMessage.success("数据导入成功"); // 默认成功消息
  }
  closedataDialog();
};

// 处理数据导入错误
const handleDataImportError = (error) => {
  // 检查error对象中是否有msg字段，并显示对应的消息
  if (error && error.response && error.response.data && error.response.data.msg) {
    ElMessage.error(error.response.data.msg); // 使用Element UI的消息提示
  } else {
    ElMessage.error("数据导入失败"); // 默认失败消息
  }
};
const closedataDialog = () => {
      dataVisible.value = false;
    };

// 关闭对话框
const closeDialog = () => {
  visible.value = false;
};

// 文件大小限制
const beforeUpload = (file) => {
  const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isXLSX) {
    ElMessage.error('上传文件必须为 XLSX 格式!');
  }
  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过 5MB!');
  }
  return isXLSX && isLt5M;
};

// 重置操作
// const reset = () => {
//   // 可以添加重置逻辑
// };


// 表单实例
const formRef = ref();
// 是否打开弹出框
const open = ref(false);
// 弹出框标题
const title = ref("");
// 提交表单数据
let form = toRef(
  reactive({
    userId: "",
    deptId: "",
    account: "",
    username: "",
    password: "",
    mobile: "",
    email: "",
    permissions: '',
  })
);
// 表单验证
const rules = ref({
  account: [
    { required: true, message: "姓名不能为空", trigger: "blur" }
  ],
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" }
  ],
  mobile: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
      message: "请输入正确的邮箱地址",
      trigger: "blur"
    }
  ]
});

// 部门列表
const deptList = ref<any[]>();
// 角色列表
const roleList = ref([
  { label: "管理员", value: "admin" },
  { label: "普通用户", value: "user" },
]);


/**
 * 查询列表
 */
const getList = () => {
  loading.value = true;
  if (daterange.value != null && daterange.value.length > 0) {
    queryForm.startTime = daterange.value[0];
    queryForm.endTime = daterange.value[1];
  } else {
    queryForm.startTime = "";
    queryForm.endTime = "";
  }

  baseService
    .get("/sysUser/list", queryForm)
    .then((res) => {
      loading.value = false;
      if (res.code === 200) {
        list.value = res.rows;
        total.value = res.total;
      } else {
        list.value = [];
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 设置每个输入框的 `watch`，监听变化，并向后端请求数据
watch(() => queryForm.userName, debounce(getList, 500));
watch(() => queryForm.mobile, debounce(getList, 500));
watch(() => queryForm.email, debounce(getList, 500));
watch(() => queryForm.account, debounce(getList, 500));
/**
 * 表单重置
 */
function reset() {
  form.value = {
    userId: "",
    deptId: "",
    account: "",
    username: "",
    password: "",
    mobile: "",
    email: "",
    permissions: "",
  };

  nextTick(() => {
    formRef.value?.resetFields();
  });
}

/**
 * 新增按钮操作
 */
 function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加";
}

/**
 * 修改按钮操作
 * @param id 主键
 */
function handleUpdate(id: string) {
  open.value = true;
  title.value = "修改";
  reset();
  baseService.get(`/sysUser/info/${id}`).then((res) => {
    form.value = res.data;
  });
}

/**
 * 删除按钮操作
 * @param id 主键
 */
function handleDelete(id: any) {
  ElMessageBox.confirm("确认要删除当前项吗?", "提示").then(() => {
    baseService.delete(`/sysUser/delete`, id).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        getList();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

/**
 * 提交按钮
 */
 function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    const api = title.value === "添加" ? `/sysUser/add` : `/sysUser/update`;
    baseService.post(api, form.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        open.value = false;
        getList();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

/**
 * 重置按钮操作
 */
function handleReset() {
  queryForm.userName = "";
  queryForm.account = "";
  queryForm.mobile = "";
  queryForm.email = "";
  daterange.value = [];
  getList();  // 重新获取列表数据
}

/**
 * 下载导入模板
 */
function downloadTemplate() {
  baseService.get("/common/getLatestTemplateUrl").then((res) => {
    if (res.code === 200) {
      window.location.href = res.data;
      ElMessage.success("模板下载成功");
    } else {
      ElMessage.error(res.msg);
    }
  });
}



/**
 * 重置密码
 */
function resetPassword(userId: string) {
  ElMessageBox.confirm("确认要重置密码吗?", "提示").then(() => {
    baseService.post(`/sysUser/resetPassword`, { userId }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

/**
 * 查询部门列表
 */
const getDeptList = () => {
  baseService.get("/sysUser/deptList").then((res) => {
    if (res.code === 200) {
      deptList.value = res.data;
    }
  });
};


onMounted(() => {
  getList();
  getDeptList();});
</script>
<style scoped>
/* 表格整体样式 */
.el-table {
  background-color: #fff;
  font-size: 14px;
  transition: all 0.3s;
}

/* 表头样式 */
.el-table__header-wrapper th {
  background-image: linear-gradient(to right, #f0f9ff, #e5eaff);
  color: #333;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
}

/* 行悬停效果 */
.el-table .el-table__body-wrapper tr:hover {
  background-color: #f0f9ff;
  transition: background-color 0.2s ease;
}

/* 状态标签样式 */
.tag-danger {
  background-color: #ff6b6b !important;
  color: #fff !important;
  border-radius: 4px;
  font-weight: 500;
}
.tag-active {
  background-color: #4caf50 !important;
  color: #fff !important;
  border-radius: 4px;
  font-weight: 500;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 5px;
}
.button-group .el-button {
  padding: 8px 12px;
  border-radius: 4px;
  font-weight: 500;
  min-width: 60px;
  transition: all 0.2s;
}
.btn-design {
  background-color: #3b82f6;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.btn-activate {
  background-color: #4caf50;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.btn-suspend {
  background-color: #ff9800;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.btn-view {
  background-color: #5c6bc0;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.btn-delete {
  background-color: #e57373;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.button-group .el-button:hover {
  opacity: 0.9;
  transform: scale(1.02);
}

/* 无信息提示样式 */
.empty-info {
  color: #999;
  font-size: 14px;
  text-align: center;
  margin: 0;
  font-weight: 500;
}

/* 按钮组样式 */
.action-buttons {
  display: flex;
  justify-content: left;
  gap: 10px; /* 调整按钮之间的间距 */
  margin-bottom: 10px; /* 与表格之间的间距 */
}

/* 自定义按钮样式 */
.custom-btn {
  padding: 8px 12px;
  border-radius: 4px;
  font-weight: 500;
  min-width: 60px;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 统一的阴影效果 */
}

/* 按钮悬浮效果 */
.custom-btn:hover {
  opacity: 0.9;
  transform: scale(1.02);
}

/* 图标样式 */
.icon {
  margin-right: 5px; /* 调整图标与文字之间的距离 */
}

/* 不同类型的按钮颜色 */
.custom-btn.primary {
  background-color: #409eff;
  color: #fff;
}
.custom-btn.success {
  background-color: #67c23a;
  color: #fff;
}

</style>